require('events').EventEmitter.defaultMaxListeners = 50;
const server = require('http').createServer();
const io = require('socket.io')(server, {
  cors: {
    origin: "*"
  }
});
const Os = require('os');
const port = 3001;
server.listen(port);
// 获取本机ip
function getIp() {
  let ip = '';
  const ifaces = Os.networkInterfaces()

  Object.keys(ifaces).forEach(function (ifname) {
    let alias = 0

    ifaces[ifname].forEach(function (iface) {
      if ('IPv4' !== iface.family || iface.internal !== false) return
      if (alias >= 1) {
        ip = iface.address
      } else {
        ip = iface.address
      }
      ++alias
    })
  })
  return ip
}

// 创建socket.io
async function createChatSocketIO(option) {
  return new Promise((resolve, reject) => {
    const { userID, namespaceName } = option;
    if (!userID) throw new Error('userID is required');
    if (!namespaceName) throw new Error('namespaceName:/users/用户ID')
    let nsp = io.of(namespaceName);
    nsp.on('connection', function (socket) {
      socket.emit('receive', JSON.stringify({ msg: '连接成功' }));
      console.log('rooms', socket.rooms);
      resolve({
        socket,
        url: `http://${getIp()}:${port}/${namespaceName}`,
        nsp
      })
    });
  })
}

module.exports = createChatSocketIO;

